package hello.app.model;

import hello.app.model.data.CallHistory;

import java.util.Date;

import android.content.ContentResolver;
import android.database.Cursor;
import android.provider.CallLog;

public class CallHistoryModel implements Model<CallHistory> {

	private CallHistory[] mHistories = null;
	private ContentResolver mContentResolver;

	CallHistoryModel(ContentResolver contentResolver) {
		mContentResolver = contentResolver;
	}

	public CallHistory[] find(String[] fields, String conditions, String order) {
		Cursor c = mContentResolver.query(
				CallLog.Calls.CONTENT_URI,
				fields,
				conditions, null, order);
		int count = c.getCount();
		if(count == 0){
			mHistories = null;
		}else{
			mHistories = new CallHistory[c.getCount()];
			for(int i = 0; i < count; i++){
				c.moveToPosition(i);
				Date date = new Date(c.getLong(2));
				mHistories[i] = new CallHistory(c.getString(4), c.getString(0), c.getString(1), date.toLocaleString(), c.getInt(3));
			}
		}
		return mHistories;
	}

	public CallHistory[] findAll() {
		Cursor c = mContentResolver.query(
				CallLog.Calls.CONTENT_URI,
		   		new String[]{
					CallLog.Calls.CACHED_NAME,
					CallLog.Calls.NUMBER,
					CallLog.Calls.DATE,
					CallLog.Calls.TYPE,
					CallLog.Calls._ID,
				},
				null, null, CallLog.Calls.DEFAULT_SORT_ORDER);
		int count = c.getCount();
		if(count == 0){
			mHistories = null;
		}else{
			mHistories = new CallHistory[c.getCount()];
			for(int i = 0; i < count; i++){
				c.moveToPosition(i);
				Date date = new Date(c.getLong(2));
				mHistories[i] = new CallHistory(c.getString(4), c.getString(0), c.getString(1), date.toLocaleString(), c.getInt(3));
			}
		}
		return mHistories;
	}


	public CallHistory findById(long id) {
		// TODO 自動生成されたメソッド・スタブ
		return null;
	}

	public boolean save(CallHistory data) {
		// TODO 自動生成されたメソッド・スタブ
		return false;
	}

	public boolean delete(String id) {
		final String where = CallLog.Calls._ID + "=" + id;
		mContentResolver.delete(CallLog.Calls.CONTENT_URI, where, null);
		return true;
	}

	public boolean delete(long id) {
		return delete(String.valueOf(id));
	}

}
